/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.suman.bbcticker.activity;

import java.net.URL;
import java.net.URLConnection;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.webkit.WebView;

import com.suman.bbcticker.R;

/**
 * Demonstrates the use of non-focusable views.
 */
public class FullNewsWebViewActivity extends Activity {
	private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	private ProgressDialog mProgressDialog;
	private WebView webView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.focus_1);
		Intent launchIntent = getIntent();
		Bundle extras = launchIntent.getExtras();
		if (extras != null) {
			mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
		}

		webView = (WebView) findViewById(R.id.rssWebView);
		try {
			// TODO show loading dialog
			// Kick off asynctask
			showDialog(mAppWidgetId);
			new FullWebPageReaderAsyncTask().execute("testurl");

			// parseBodyOfNews(
			// "http://news.bbc.co.uk/1/hi/world/europe/8297757.stm");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private class FullWebPageReaderAsyncTask extends AsyncTask<String, Void, String> {
		@Override
		protected void onPostExecute(String result) {
			webView.loadData("<html><body>" + result + "</body></html>", "text/html", "utf-8");
			mProgressDialog.dismiss();
		}

		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String parseBodyOfNews = parseBodyOfNews("");
			System.out.println("Parsed body is.." + parseBodyOfNews);
			return parseBodyOfNews;
		}

	}

	private String parseBodyOfNews(String url) {
		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			factory.setValidating(false);
			XmlPullParser xpp = factory.newPullParser();
			xpp.setFeature(Xml.FEATURE_RELAXED, true);

			URLConnection conn = new URL("http://news.bbc.co.uk/1/hi/world/europe/8297757.stm").openConnection();
			conn.setConnectTimeout(R.string.rssfeed_connecttimeout);
			conn.setReadTimeout(R.string.rssfeed_readtimeout);

			boolean pTagFound = false;
			xpp.setInput(conn.getInputStream(), "utf-8");
			int eventType = xpp.getEventType();
			String result = "";
			int pTagCount = 0;
			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG) {
					if (xpp.getName().equals("p")) {
						if ("first".equals(xpp.getAttributeValue(null, "class"))) {
							pTagFound = true;
						}
						pTagCount++;
					}
				} else if (eventType == XmlPullParser.END_TAG) {

					if (xpp.getName().equals("p")) {
						pTagCount--;

						if (pTagFound && pTagCount == 1) {

							pTagFound = false;
							break;
						}

					}

				} else if (eventType == XmlPullParser.TEXT) {
					if (pTagFound) {
						result += xpp.getText();
					}

				}
				eventType = xpp.next();
			}

			return result;
		} catch (Throwable t) {
			t.printStackTrace();
		}
		return null;

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setMessage("Please wait while loading...");
		mProgressDialog.setIndeterminate(true);
		mProgressDialog.setCancelable(true);
		return mProgressDialog;
	}

	/*
	 * private Handler handler = new Handler() {
	 * 
	 * @Override public void handleMessage(Message msg) { Log.e(TAG,
	 * "Dismissing Dialog.."); mProgressDialog.dismiss(); finish(); } };
	 * 
	 * @Override protected Dialog onCreateDialog(int id) { Log.e(TAG,
	 * "Showing Dialog..");
	 * 
	 * mProgressDialog = new ProgressDialog(this);
	 * mProgressDialog.setMessage("Please wait while loading...");
	 * mProgressDialog.setIndeterminate(true);
	 * mProgressDialog.setCancelable(true); return mProgressDialog; }
	 */
}
